﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Dynamic;

namespace UIT.Controls.Data
{
    public class LinqDataProvider : IParametersDataProvider
    {
        public string Where { get; set; }

        public ParameterCollection SelectParameters { get; private set; }

        public ParameterCollection UpdateParameters { get; private set; }

        public ParameterCollection InsertParameters { get; private set; }

        public ParameterCollection DeleteParameters { get; private set; }

        public string Id { get; set; }

        public bool CanSelect
        {
            get { return Query != null; }
        }

        public bool CanInsert
        {
            get { return false; }
        }

        public bool CanDelete
        {
            get { return false; }
        }

        public bool CanUpdate
        {
            get { return false; }
        }

        public System.Collections.IEnumerable Select(SelectArgument arg)
        {
            if (!CanSelect)
                throw new InvalidOperationException("Please specify a Query before selecting data");
            if (Query == null)
                return System.Linq.Enumerable.Empty<object>();
            var queryable = Query.AsQueryable();
            if (arg.RequestedOperations.HasFlag(Operations.Page))
            {
                arg.TotalRowCount = queryable.Count();
                queryable = queryable.Skip(arg.StartRowIndex).Take(arg.MaximumRows);
            }
            if (arg.RequestedOperations.HasFlag(Operations.Sort))
                queryable = queryable.OrderBy(arg.SortExpression);
            return queryable;
        }

        public void Update()
        {
            throw new NotImplementedException();
        }

        public void Insert()
        {
            throw new NotImplementedException();
        }

        public void Delete()
        {
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            if (SelectParameters != null)
                SelectParameters.Dispose();
            if (InsertParameters != null)
                InsertParameters.Dispose();
            if (DeleteParameters != null)
                DeleteParameters.Dispose();
            if (UpdateParameters != null)
                UpdateParameters.Dispose();
        }

        public IQueryable Query { get; set; }

        public IControl Parent
        {
            get;
            set;
        }

        #region IDataProvider Members


        public Operations SupportedOperations
        {
            get { return Query != null ? Operations.Select | Operations.Sort | Operations.Page : Operations.None; }
        }

        #endregion
    }
}
